package top.lgd.controller.study;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.lgd.base.LgdConstants;
import top.lgd.base.LgdResult;
import top.lgd.base.LgdTable;
import top.lgd.controller.LgdController;
import top.lgd.pojo.entity.study.Catalog;
import top.lgd.pojo.res.TreeRes;
import top.lgd.pojo.res.study.CatalogRes;
import top.lgd.service.study.CatalogService;

/**
 * @author YYJ
 * @version 1.0
 * @since 2023/12/19 19:12
 */
@RestController
@RequestMapping("/admin/studyCatalog")
public class CatalogAdminController extends LgdController {

    @Autowired
    private CatalogService catalogService;

    /**
     * 查询学习目录树
     *
     * @return
     */
    @PostMapping("/queryCatalogTree")
    public LgdTable<TreeRes> queryCatalogTree() {
        return getTable(catalogService.genCatalogTree(current().getId()));
    }

    /**
     * 查询学习目录树列表
     *
     * @return
     */
    @PostMapping("/queryTreeList")
    public LgdTable<CatalogRes> queryTreeList() {
        return getTable(catalogService.genTreeList(current().getId()));
    }

    /**
     * 添加编辑学习目录
     *
     * @param catalog 学习目录 对象
     * @return
     */
    @PostMapping("addUpdate")
    public LgdResult<Catalog> addUpdate(@RequestBody Catalog catalog) {
        if (null == catalog.getId()) {
            if (null == catalog.getParentid() || LgdConstants.LONG_ZERO == catalog.getParentid()) {
                catalog.setAncestors(LgdConstants.LONG_ZERO + LgdConstants.ANCESTORS_SPLIT);
            } else {
                Catalog parentCatalog = catalogService.queryCatalog(catalog.getParentid());
                if (null == parentCatalog) {
                    return LgdResult.fail("上级目录错误");
                }
                catalog.setAncestors(parentCatalog.getAncestors() + parentCatalog.getId() + LgdConstants.ANCESTORS_SPLIT);
            }
        }
        catalogService.saveOrUpdate(catalog, current().getId());
        return LgdResult.success(catalog);
    }

    /**
     * 删除学习目录
     *
     * @param id 个人计划ID
     * @return
     */
    @PostMapping("remove")
    public LgdResult<String> remove(@RequestParam Long id) {
        if (catalogService.remove(id, current().getId())) {
            return LgdResult.success("删除学习目录成功");
        }
        return LgdResult.fail("删除学习目录失败");
    }
}